package io.zim.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.zim.common.annotation.DataFilter;
import io.zim.common.exception.RRException;
import io.zim.common.utils.Constant;
import io.zim.common.utils.PageUtils;
import io.zim.common.utils.Query;
import io.zim.modules.sys.dao.SysRoleDao;
import io.zim.modules.sys.entity.SysRoleEntity;
import io.zim.modules.sys.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 角色
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:45:12
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleDeptService sysRoleDeptService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String roleName = (String)params.get("roleName");
		Long createUserId = (Long)params.get("createUserId");

		Page<SysRoleEntity> page = (Page<SysRoleEntity>) this.page(
				new Query<SysRoleEntity>(params).getPage(),
				new QueryWrapper<SysRoleEntity>()
						.like(StringUtils.isNotBlank(roleName),"role_name", roleName)
						.eq(createUserId != null,"create_user_id", createUserId)
		);

		return new PageUtils(page);
	}

	@Override
	@DataFilter(userAlias = "r.create_user_id", deptAlias = "r.dept_id", self = false)
	public List<SysRoleEntity> queryList(Map<String, Object> map) {
		return baseMapper.queryList(map);
	}

	@Override
	@DataFilter(userAlias = "r.create_user_id", deptAlias = "r.dept_id", self = false)
	public int queryTotal(Map<String, Object> map) {
		return baseMapper.queryTotal(map);
	}

	@Override
    @Transactional(rollbackFor = Exception.class)
	public boolean insert(SysRoleEntity role) {
		role.setCreateTime(new Date());
        boolean isOk = this.save(role);

		//检查权限是否越权
		checkPrems(role);

		//保存角色与菜单关系
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

		//保存角色与部门关系
		sysRoleDeptService.saveOrUpdate(role.getRoleId(), role.getDeptIdList());
		return isOk;
	}

	@Override
    @Transactional(rollbackFor = Exception.class)
	public boolean update(SysRoleEntity role) {
		boolean isOk = this.updateById(role);

		//检查权限是否越权
		checkPrems(role);

		//更新角色与菜单关系
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

		//保存角色与部门关系
		sysRoleDeptService.saveOrUpdate(role.getRoleId(), role.getDeptIdList());
        return isOk;
	}

	@Override
    @Transactional(rollbackFor = Exception.class)
	public int removeByIds(Long[] roleIds) {
        return baseMapper.deleteBatch(roleIds);
	}

    @Override
	public List<Long> queryRoleIdList(Long createUserId) {
		return baseMapper.queryRoleIdList(createUserId);
	}

	/**
	 * 检查权限是否越权
	 */
	private void checkPrems(SysRoleEntity role){
		//如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
		if (role.getCreateUserId() == Constant.SUPER_ADMIN) {
			return ;
		}
		
		//查询用户所拥有的菜单列表
		List<Long> menuIdList = sysUserService.queryAllMenuId(role.getCreateUserId());
		
		//判断是否越权
		if (!menuIdList.containsAll(role.getMenuIdList())) {
			throw new RRException("新增角色的权限，已超出你的权限范围");
		}
	}
}
